package admin

import (
	"context"
	"grpc.getaway.adminspro.padmins.com/internal/rpc/utils/database"
	"grpc.getaway.adminspro.padmins.com/pkg/config/businessError"
	"grpc.getaway.adminspro.padmins.com/pkg/libs/utils"
	pbAdmin "grpc.getaway.adminspro.padmins.com/pkg/proto/admin"
)

func (rpc *admin) AdminRoleResource(ctx context.Context, pb *pbAdmin.AdminRoleResourceReq) (*pbAdmin.AdminRoleResourceResp, error) {
	Db := database.Db.GetDefaultDb(ctx)
	rows, dbErr := Db.Query("select resource_id from admin_role_resource_access where role_id in (?)", pb.Pid)

	if dbErr != nil {
		return nil, businessError.ErrorInfoToRpcError(businessError.DbError(dbErr))
	}

	resourceIds := utils.ArrayColumn(rows, "resource_id")
	selectResourceIds := []interface{}{}
	if pb.Id != 0 {
		rows, dbErr := Db.Query("select resource_id from admin_role_resource_access where role_id in (?)", pb.Id)
		if dbErr != nil {
			return nil, businessError.ErrorInfoToRpcError(businessError.DbError(dbErr))
		}
		selectResourceIds = utils.ArrayColumn(rows, "resource_id")
	}

	if utils.InArray(int64(0), resourceIds) {
		rows, dbErr = Db.Query("select * from admin_resource")
		if dbErr != nil {
			return nil, businessError.ErrorInfoToRpcError(businessError.DbError(dbErr))
		}
	} else if len(resourceIds) > 0 {
		rows, dbErr = Db.Query("select * from admin_resource where id in (?)", resourceIds)
		if dbErr != nil {
			return nil, businessError.ErrorInfoToRpcError(businessError.DbError(dbErr))
		}
	} else {
		rows = []map[string]interface{}{}
	}

	ids := utils.ArrayColumn(rows, "id")
	pids := utils.ArrayColumn(rows, "pid")
	rowLength := len(rows)
	resp := &pbAdmin.AdminRoleResourceResp{}
	resp.Rows = make([]*pbAdmin.AdminRoleResourceResp_AdminResource, rowLength)
	for i, row := range rows {
		resp.Rows[i] = &pbAdmin.AdminRoleResourceResp_AdminResource{
			Id:         row["id"].(int64),
			Pid:        row["pid"].(int64),
			Type:       int32(row["type"].(int64)),
			Path:       row["path"].(string),
			Resource:   row["resource"].(string),
			Title:      row["title"].(string),
			Icon:       row["icon"].(string),
			Remark:     row["remark"].(string),
			Badge:      row["badge"].(string),
			Weigh:      row["weigh"].(int64),
			Status:     int32(row["status"].(int64)),
			CreateTime: row["create_time"].(string),
			UpdateTime: row["update_time"].(string),
			Selected:   false,
		}
		if !utils.InArray(row["pid"], ids) {
			resp.Rows[i].Pid = 0
		}
		if !utils.InArray(row["id"], pids) {
			resp.Rows[i].Selected = utils.InArray(row["id"], selectResourceIds)
		}
	}

	resp.Total = int64(rowLength)

	return resp, nil
}
